import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model, Types } from 'mongoose';
import { WebsiteMongoService } from './website-mongo.service';
import { StatsMongoService } from './stats-mongo.service';
import { IpMongoService } from './ip-mongo.service';
import { SessionMongoService } from './session-mongo.service';
import { LogService } from './log.service';
import UAParser from 'ua-parser-js';
import * as fs from 'fs';
import * as path from 'path';
import { PageView, PageViewDocument } from './schemas/page-view.schema';
import { Website, WebsiteDocument } from './schemas/website.schema';

@Injectable()
export class TrackingMongoService {
  constructor(
    private websiteService: WebsiteMongoService,
    private statsService: StatsMongoService,
    private ipService: IpMongoService,
    private sessionService: SessionMongoService,
    private logService: LogService,
    @InjectModel(PageView.name)
    private pageViewModel: Model<PageViewDocument>,
    @InjectModel(Website.name)
    private websiteModel: Model<WebsiteDocument>,
  ) {}

  // 网站管理 - 适配MongoDB ObjectId
  createWebsite(dto) { return this.websiteService.createWebsite(dto); }
  updateWebsite(id, dto) { return this.websiteService.updateWebsite(id, dto); }
  deleteWebsite(id) { return this.websiteService.deleteWebsite(id); }
  deleteAllWebsites() { return this.websiteService.deleteAllWebsites(); }
  getAllWebsites() { return this.websiteService.getAllWebsites(); }
  getWebsiteById(id) { return this.websiteService.getWebsiteById(id); }
  getWebsiteByTrackingId(trackingId) { return this.websiteService.getWebsiteByTrackingId(trackingId); }
  getEmbedCode(id) { return this.websiteService.getEmbedCode(id); }

  // 统计 - 适配MongoDB ObjectId
  getWebsiteStats(id, query) { return this.statsService.getWebsiteStats(id, query); }
  getWebsiteSummary(id, query) { return this.statsService.getWebsiteSummary(id, query); }
  getWebsiteTrend(id, query) { return this.statsService.getWebsiteTrend(id, query); }

  // IP - 适配MongoDB ObjectId
  getIpVisits(ip, websiteId, startDate, endDate) { return this.ipService.getIpVisits(ip, websiteId, startDate, endDate); }
  getWebsiteIps(websiteId) { return this.ipService.getWebsiteIps(websiteId); }

  // 会话
  getSessionDetails(sessionId) { return this.sessionService.getSessionDetails(sessionId); }

  // 日志
  getLogStats() { return this.logService.getLogStats(); }
  getBusinessLoopLogs(trackingId, date) { return this.logService.getBusinessLoopLogs(trackingId, date); }
  checkBusinessLoopIntegrity(trackingId, date) { return this.logService.checkBusinessLoopIntegrity(trackingId, date); }

  // 页面访问埋点 - 使用MongoDB
  async trackPageview(trackPageviewDto, ip: string, userAgent: string) {
    const website = await this.websiteService.getWebsiteByTrackingId(trackPageviewDto.trackingId);
    if (!website) return null;

    let browser: string | undefined;
    let os: string | undefined;
    let device: string | undefined;

    try {
      if (userAgent) {
        const parser = new UAParser(userAgent);
        const result = parser.getResult();
        browser = result.browser?.name || undefined;
        os = result.os?.name || undefined;
        device = result.device?.type || undefined;
      }
    } catch (e) {
      // UA 解析失败时不影响页面访问记录插入
    }

    let screenSize: string | undefined;
    const custom = trackPageviewDto?.customData || {};
    // 允许前端脚本通过 customData 直接传入解析结果，覆盖 UAParser 的结果
    if (custom.browser) {
      browser = custom.browser;
    }
    if (custom.os) {
      os = custom.os;
    }
    if (custom.device) {
      device = custom.device;
    }
    if (custom.screenWidth && custom.screenHeight) {
      screenSize = `${custom.screenWidth}x${custom.screenHeight}`;
    }
    const language = custom.language;

    const pageView = new this.pageViewModel({
      websiteId: website._id,
      url: trackPageviewDto.url,
      title: trackPageviewDto.title,
      referrer: trackPageviewDto.referrer,
      ip,
      userAgent,
      sessionId: trackPageviewDto.sessionId,
      customData: trackPageviewDto.customData,
      country: undefined,
      city: undefined,
      browser,
      os,
      device,
      screenSize,
      language,
    });

    return pageView.save();
  }

  // 返回埋点脚本
  getTrackingScript(): string {
    try {
      const scriptPath = path.join(__dirname, '..', '..', '..', 'src', 'modules', 'tracking', 'tracking-script.js');
      return fs.readFileSync(scriptPath, 'utf8');
    } catch (error) {
      return 'console.log("DevOps BI tracking script loaded")';
    }
  }
}
